package com.teach.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;


public class StringArrayTypeHandler extends BaseTypeHandler<String[]>{

	private ObjectMapper mapper = new ObjectMapper();

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType)
			throws SQLException {
		try {
			ps.setString(i, mapper.writeValueAsString(parameter));
		} catch (JsonProcessingException e) {
			ps.setString(i, "[]");
		}
	}

	@Override
	public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return get(rs.getString(columnName));
	}

	@Override
	public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return get(rs.getString(columnIndex));
	}

	@Override
	public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return get(cs.getString(columnIndex));
	}
	
	private String[] get(String str) throws SQLException{
		try {
			if(str==null){
				return null;
			}
			try {
				List<String> list = null;
				JavaType type = mapper.getTypeFactory().constructParametricType(List.class, String.class);
				list = mapper.readValue(str, type);
				return list.toArray(new String[0]);
			}catch (Exception e) {
				return new String[0];
			}
		} catch (Exception e) {
			throw new SQLException(e.getMessage(), e);
		}
	}

	 



}
